package com.cheli.aclservice.controller;


import com.cheli.aclservice.entity.Role;
import com.cheli.aclservice.entity.UserRole;
import com.cheli.aclservice.service.RoleService;
import com.cheli.aclservice.service.UserRoleService;
import com.cheli.commonutils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cheli.commonutils.R;
import com.cheli.security.entity.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@RestController
@RequestMapping("/admin/acl/role")
@CrossOrigin
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @ApiOperation(value = "获取角色分页列表")
    @PostMapping("{page}/{limit}")
    public R index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            UserRole role) {
        Page<UserRole> pageParam = new Page<>(page, limit);
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(role.getUserId())) {
            wrapper.like("user_id",role.getUserId());
        }
        userRoleService.page(pageParam,wrapper);
        return R.ok().data("items", pageParam.getRecords()).data("total", pageParam.getTotal());
    }

    @ApiOperation(value = "设置用户权限")
    @GetMapping("/{userId}/{role}")
    public R setRoleByUserId(
            @PathVariable String userId,
            @PathVariable String role) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserRole userRole = userRoleService.getOne(queryWrapper);
        if(userRole != null) {
            userRole.setRoleId(role);
            userRoleService.updateById(userRole);
        }
        else{
            UserRole userRole1 = new UserRole();
            userRole1.setRoleId(role);
            userRole1.setUserId(userId);
            userRoleService.save(userRole1);
        }
        return R.ok();
    }

}

